package com.dialog.ringsdk.demo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dialog.ringsdk.R;
import com.dialog.suotalib.global.SuotaProfile;
import com.dialog.suotalib.interfaces.callbacks.ISuotaScanner;
import com.dialog.suotalib.ring.RingManagement;
import com.dialog.suotalib.suota.SuotaManager;
import com.dialog.suotalib.suota.SuotaManagerCallback;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ISuotaScanner {
    private static final String TAG = "";
    Button button, btn_mode, btn_kongzhong;
    TextView tv_status,tv_valve;
    RecyclerView recyclerView;
    RingManagement ringManagement;
    private List<BluetoothDevice> scannedDevices = new ArrayList();
    MyBluetoothDeviceAdapter adapter;
    private SuotaManager suotaManager;
    private Handler connectingTimeoutHandler;
    private List<String> mPermissionList = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.btn_sao_miao);
//        btn_mode = findViewById(R.id.btn_mode);
//        btn_kongzhong = findViewById(R.id.btn_kongzhong);
        recyclerView = findViewById(R.id.rv_device);
        tv_status = findViewById(R.id.tv_status);
        tv_valve = findViewById(R.id.tv_valve);
        adapter = new MyBluetoothDeviceAdapter(scannedDevices, this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        initPermission();

        connectingTimeoutHandler = new Handler();

        adapter.setOnItemClickListener(new MyBluetoothDeviceAdapter.onItemClickListener() {
            @Override
            public void onItemClick(BluetoothDevice bluetoothDevice) {
                if (ringManagement.getState().equals(SuotaManager.ManagerState.CONNECTING)) {
                    Toast.makeText(MainActivity.this, "正在连接", Toast.LENGTH_LONG).show();
                    tv_status.setText("正在连接");
                    return;
                }
                ringManagement.connect(getLifecycle(), MainActivity.this, bluetoothDevice, new SuotaManagerCallback() {
                    @Override
                    public void complete() {
                        tv_status.setText("已连接");
                        Toast.makeText(MainActivity.this, "已连接", Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onPythonData(Integer data) {
                        Log.e("py   recognize 结果", data + "");
                            tv_valve.setText("结果:"+data);
                    }
                    @Override
                    public void onConnectionStateChange(SuotaProfile.SuotaManagerStatus newStatus) {
                        connectingTimeoutHandler.removeCallbacksAndMessages(null);
                        if (newStatus == SuotaProfile.SuotaManagerStatus.DISCONNECTED) {
                            Toast.makeText(MainActivity.this, "断开连接", Toast.LENGTH_LONG).show();
                            tv_status.setText("已断开");
                            scannedDevices.clear();
                            adapter.notifyDataSetChanged();
                        } else if (newStatus == SuotaProfile.SuotaManagerStatus.CONNECTED) {

                        }
                    }
                });
                connectingTimeoutHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.unable_to_connect_toast, Toast.LENGTH_LONG).show();
                    }
                }, 20000);
            }
        });
        ringManagement =  RingManagement.getRingManagement(getLifecycle(), this, savedInstanceState);

        button.setText(ringManagement.isScanning() ? R.string.menu_stop_scan : R.string.menu_scan);
        button.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View v) {
                if (ringManagement.isScanning()) {

                    Log.d(TAG, "Stop scanning...");
                    ringManagement.stopScan();
                } else {
                    Log.d(TAG, "scanning...");
                    ringManagement.scan(MainActivity.this);
                    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    for (BluetoothDevice device : bluetoothAdapter.getBondedDevices()) {
                        scannedDevices.add(device);
                        adapter.notifyDataSetChanged();
                    }
                }

            }
        });
//        btn_mode.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ringManagement.setMode(ringManagement.DESKTOP);
//            }
//        });
//        btn_kongzhong.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ringManagement.setMode(ringManagement.SPACE);
//            }
//        });
    }

    @Override
    public void onFailure(SuotaProfile.ScanFailure failure) {
        switch (failure) {
            case BLE_NOT_SUPPORTED:  //设备不支持低功耗蓝牙
                Log.e(TAG, "Bluetooth Low Energy not supported");
                Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_LONG).show();
                finish();
                break;
            case RESCANNING_TOO_SOON: //正在扫描
                Log.d(TAG, "Constantly scanning");
                Toast.makeText(this, R.string.constantly_scanning, Toast.LENGTH_SHORT).show();
                break;
            default:
                ringManagement.stopScan();
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onDeviceScan(BluetoothDevice bluetoothDevice, int rssi, byte[] scanRecord) {

        if (!scannedDevices.contains(bluetoothDevice)) {
            scannedDevices.add(bluetoothDevice);
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onScanStatusChange(SuotaProfile.ScanStatus newStatus) {
        if (newStatus == SuotaProfile.ScanStatus.STOPPED) {  //停止扫描
            button.setText("开始搜索");
            Toast.makeText(MainActivity.this, "停止扫描", Toast.LENGTH_SHORT).show();
        } else {  //  开始扫描

            button.setText("停止搜索");
            Toast.makeText(MainActivity.this, "开始扫描", Toast.LENGTH_SHORT).show();
        }
    }
    @SuppressLint("RestrictedApi")
    private void initPermission(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
            // Android 版本大于等于 Android12 时
            // 只包括蓝牙这部分的权限，其余的需要什么权限自己添加
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            mPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            mPermissionList.add(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
        } else {
            // Android 版本小于 Android12 及以下版本
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            mPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            mPermissionList.add(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
        }

        if(mPermissionList.size() > 0){
            ActivityCompat.requestPermissions(this,mPermissionList.toArray(new String[0]),1001);
        }
    }


}